<script lang="ts" setup>
import { getPatientConsultOrderListAPI, postPatientConsultPayAPI } from '@/apis/consult'
import { cancelPatientMedicineOrderAPI, deletePatientMedicineOrderAPI } from '@/apis/order';
import {
  OrderStatus,
  type ConsultOrderItem,
  type GetPatientConsultOrderListData,
  type GetPatientConsultOrderListParams,
} from '@/types/consult'
import { ref } from 'vue'

// 接收父组件传递的参数
const props = defineProps<{
  type?: number
}>()
// 定义查询参数
const query = ref<Required<GetPatientConsultOrderListParams>>({
  type: props.type ?? 0,
  current: 1,
  pageSize: 10,
})
// 动态修改加载状态
const loadMoreStatus = ref<UniHelper.UniLoadMoreStatus>()
// 订单列表数据
const orderList = ref<ConsultOrderItem[]>([])
const total = ref(0)
const pageTotal = ref(0)
// 获取订单列表
const getPatientConsultOrderList = async (isMore = false) => {
  // 加载中
  loadMoreStatus.value = 'loading'
  const res = await getPatientConsultOrderListAPI(query.value)
  // console.log(res)
  // 加载完成
  // 如果是加载更多，则追加数据
  if (isMore) {
    orderList.value.push(...res.data.rows)
  } else {
    orderList.value = res.data.rows
  }
  total.value = res.data.total
  pageTotal.value = res.data.pageTotal
  // 加载更多数据

}
const getMoreData = async () => {
  // 如果当前页已经是最后一页，则不再加载
  if (query.value.current >= pageTotal.value) return
  // 页码加1
  query.value.current++
  // 加载更多数据
  await getPatientConsultOrderList(true)
}
getPatientConsultOrderList()

// 下拉刷新
const refreshTriggered = ref(false)
const onRefresh = async () => {
  // 开启下拉刷新状态
  refreshTriggered.value = true
  // 重置页码
  query.value.current = 1
  // 重新加载数据
  await getPatientConsultOrderList()
  // 关闭下拉刷新状态
  refreshTriggered.value = false
}

// 是否显示更多
const activeShowMoreId = ref('')
// 取消订单 后端取消：调用接口，前端取消：修改状态
const cancelOrder = async (orderId: string) => {
  // 后端取消
  const res =  await cancelPatientMedicineOrderAPI(orderId)
  // console.log(res);
  // 前端取消
  orderList.value = orderList.value.filter(item => item.id !== orderId)
}

// 删除订单
const deleteOrder = async (orderId: string) => {
  const res =  await deletePatientMedicineOrderAPI(orderId)
  // console.log(res);
  // 前端删除
  orderList.value = orderList.value.filter(item => item.id !== orderId)
}
// 去支付 后端支付：调用接口，前端支付：跳转支付页面，支付宝支付
const toPay = async (orderId: string) => {
  const res = await postPatientConsultPayAPI({orderId})
  // console.log(res);
}
// 问诊记录 跳转到问诊室
const toConsultRoom = (orderId: string) => {
  uni.navigateTo({
    url: `/subpkg_consult/pages/room/room?orderId=${orderId}`
  })
}
</script>

<template>
  <scroll-view
    refresher-enabled
    :refresher-triggered="refreshTriggered"
    @refresherrefresh="onRefresh"
    refresher-background="#f6f6f6"
    class="uni-scroll-view"
    scroll-y
    @click="activeShowMoreId = ''"
    @scrolltolower="getMoreData"
  >
    <view class="consult-list">
      <view class="consult-list-item" v-for="item in orderList" :key="item.id">
        <view class="consult-header">
          <view class="label">
            <image class="doctor-avatar" src="/static/uploads/doctor-avatar.jpg" />
            <text>{{ item.typeValue }}</text>
          </view>
          <text
            class="status color-3"
            :class="{
              'color-1': item.status === OrderStatus.DaiZhiFu,
              'color-2': [OrderStatus.DaiJieZhen, OrderStatus.ZiXunZhong].includes(item.status),
              'color-3': [OrderStatus.YiWanCheng, OrderStatus.YiQuXiao].includes(item.status),
            }"
          >
            {{ item.statusValue }}</text
          >
        </view>
        <navigator class="consult-body" hover-class="none" 
        :url="`/subpkg_consult/pages/order_detail/order_detail?orderId=${item.id}`">
          <uni-list :border="false">
            <uni-list-item :border="false" title="病情描述" :right-text="item.illnessDesc" />
            <uni-list-item :border="false" title="价格" :right-text="`¥ ${item.payment}`" />
            <uni-list-item :border="false" title="创建时间" :right-text="item.createTime" />
          </uni-list>
        </navigator>
        <view class="consult-footer">
          <view class="uni-button more" v-if="item.status === OrderStatus.YiWanCheng">
            <text
              class="label"
              @click.stop="activeShowMoreId = activeShowMoreId === item.id ? '' : item.id"
              >更多</text
            >
            <uni-transition :show="activeShowMoreId === item.id">
              <view class="list">
                <view class="list-item">查看处方</view>
                <view class="list-item" @click="deleteOrder(item.id)">删除订单</view>
              </view>
            </uni-transition>
          </view>
          <template v-if="item.status === OrderStatus.DaiZhiFu">
            <button class="uni-button minor" @click="cancelOrder(item.id)">取消订单</button>
            <button class="uni-button" @click="toPay" >去支付</button>
          </template>

          <template v-if="item.status === OrderStatus.DaiJieZhen">
            <button class="uni-button minor" @click="cancelOrder(item.id)">取消订单</button>
            <button class="uni-button" @click="toConsultRoom(item.id)">继续咨询</button>
          </template>

          <template v-if="item.status === OrderStatus.ZiXunZhong">
            <button class="uni-button" @click="toConsultRoom(item.id)">继续咨询</button>
          </template>

          <template v-if="item.status === OrderStatus.YiWanCheng">
            <button class="uni-button minor" @click="toConsultRoom(item.id)">问诊记录</button>
            <button v-if="item.evaluateId" class="uni-button minor">查看评价</button>
            <button v-else class="uni-button">去评价</button>
          </template>

          <template v-if="item.status === OrderStatus.YiQuXiao">
            <button class="uni-button minor" @click="deleteOrder(item.id)">删除订单</button>
            <button class="uni-button" @click="toConsultRoom(item.id)">咨询其它医生</button>
          </template>
        </view>
      </view>
      <!-- 加载状态 -->
      <uni-load-more
        :status="loadMoreStatus"
        color="#C3C3C5"
        :icon-size="16"
        :content-text="{
          contentdown: '上拉显示更多',
          contentrefresh: '数据正在加载中',
          contentnomore: '没有更多数据了',
        }"
      />
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import './styles.scss';
</style>
